package com.chen.seckill.rabbitmq;

import com.chen.seckill.pojo.GoodsVO;
import com.chen.seckill.pojo.SeckillMessage;
import com.chen.seckill.pojo.SeckillOrder;
import com.chen.seckill.pojo.User;
import com.chen.seckill.resultvo.RespBean;
import com.chen.seckill.resultvo.RespBeanEnum;
import com.chen.seckill.service.IGoodsService;
import com.chen.seckill.service.IOrderService;
import com.chen.seckill.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class MQReceiver {


    @Resource
    private IGoodsService goodsService;


    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    @Resource
    private IOrderService orderService;

    /**
     * 队列
     */
    private static final String QUEUE = "seckillQueue";


    /**
     * 下单操作（在数据库生成商品订单）
     */
    @RabbitListener(queues = QUEUE)
    public void receive(String message){
        log.info("接收的信息: "+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(goodId);
        if (goodsVO.getStockCount()<1){
            return;
        }
        //判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder!=null){
            return;
        }
        //生成order订单
        orderService.seckill(user,goodsVO);

    }
}
